﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Cache.Repositories;
using IMClient.Model;
using IMClient.Model.DataBase;
using IMClient.Model.UI;
using IMClient.View;

namespace IMClient.ViewModels
{
    public partial class ContactsPageGroupsListViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<GroupViewModel> groupsList;

        [ObservableProperty]
        private ObservableCollection<GroupViewModel> filteredGroups;

        [ObservableProperty]
        private GroupViewModel? selectedGroup;

        private readonly GroupCacheRepository _groupRepository;

        public event Action<object>? CurrentViewChanged;
        public event Action? GroupsListUpdated;
        public ContactsPageGroupsListViewModel()
        {
            _groupRepository = GroupCacheRepository.Instance;
            new HttpClient();
            GroupsList = new ObservableCollection<GroupViewModel>();
            filteredGroups=new ObservableCollection<GroupViewModel>();

            GroupCreatorManagerViewModel.GroupAvatarUpdated += OnGroupAvatarUpdated;
            GroupCreatorManagerViewModel.GroupNameUpdated += OnGroupNameUpdated;

            GroupNotificationViewModel.GroupAvatarUpdated += OnGroupAvatarUpdated;
            GroupNotificationViewModel.GroupNameUpdated += OnGroupNameUpdated;

            ContactsPageViewModel.ParticipantAdded += OnGroupAdded;
            // 监听好友列表更新事件
            User.OnGroupListUpdated += () =>
            {
                _ = LoadGroupsAsync();
            };

            _ = LoadGroupsAsync();
        }

        [RelayCommand]
        private void ShowGroupDetails()
        {
            if (SelectedGroup != null)
            {
                // 根据是否为群主显示不同的视图
                if (SelectedGroup.IsCreator)
                {
                    // 显示群主管理视图
                    CurrentViewChanged?.Invoke(new GroupCreatorManagerView
                    {
                        DataContext = new GroupCreatorManagerViewModel(SelectedGroup)
                    });
                }
                else
                {
                    // 显示普通成员视图
                    CurrentViewChanged?.Invoke(new GroupDetailsView
                    {
                        DataContext = new GroupDetailsViewModel(SelectedGroup)
                    });
                }
            }
        }

        private async Task LoadGroupsAsync()
        {
            try
            {
                string userId = User.UserId ?? throw new InvalidOperationException("用户ID不能为空");

                // 从数据库加载好友列表
                var cachedGroups = await _groupRepository.GetCachedGroupsAsync(userId);
                UpdateUIGroupsList(cachedGroups);
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show($"加载好友列表失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                });
            }
        }

        private void UpdateUIGroupsList(List<GroupDataBase> groups)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                GroupsList.Clear();
                FilteredGroups.Clear();
                foreach (var group in groups)
                {
                    GroupsList.Add(new GroupViewModel
                    {
                        Id = group.GroupId,
                        Name = group.GroupName,
                        Avatar = group.GroupAvatar,
                        IsCreator = group.Creator == User.UserId
                    });
                    FilteredGroups.Add(new GroupViewModel
                    {
                        Id = group.GroupId,
                        Name = group.GroupName,
                        Avatar = group.GroupAvatar,
                        IsCreator = group.Creator == User.UserId
                    });
                }

                
                if (FilteredGroups.Count > 0)
                {
                    SelectedGroup = FilteredGroups[0];
                }
            });
        }

        public void OnGroupAvatarUpdated(string groupId, string newAvatar)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 查找对应的群
                var group = GroupsList.FirstOrDefault(g => g.Id == groupId);
                if (group != null)
                {
                    group.Avatar = newAvatar; // 更新头像

                    GroupsListUpdated?.Invoke();
                }
            });
        }

        public void OnGroupNameUpdated(string groupId, string newName)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 查找对应的群
                var group = GroupsList.FirstOrDefault(g => g.Id == groupId);
                if (group != null)
                {
                    group.Name = newName; // 更新头像

                    GroupsListUpdated?.Invoke();
                }
            });
        }

        private async void OnGroupAdded(ChatParticipantViewModel model)
        {
            await LoadGroupsAsync();
        }

    }
}
